#!/usr/bin/env bash
# NOTE execute this file at by6pms project root
# Environment Variables:
# - RELEASE_REPO_PATH: path relative to by6pms project root or a absolute path

set -euo pipefail

basepath=$(cd `dirname $0`; pwd)

. $basepath/lib.sh


if [[ -z $RELEASE_REPO_PATH ]]; then
    echo "Please specify RELEASE_REPO_PATH variable!"
    exit 1
fi

release_repo_path=$RELEASE_REPO_PATH

if yes_or_no "Empty directory $release_repo_path (exclude '.git' and '.jj' directory)?"; then
    cd $release_repo_path
    find . -mindepth 1 -maxdepth 1 ! -name '.git' ! -name '.jj' -exec rm -rf {} +
    cd -
fi

if [[ ! -f "pyproject.toml" ]]; then
    echo "Please execute this script at the by6pms project root!"
    exit 1
fi

# Build by6pms

# style
sh $basepath/compile-css-files.sh

# script
./node_modules/.bin/esbuild "./static-origin/script/**/*.ts" "./static-origin/script/**/*.js" --bundle --minify --splitting --format="esm" --outdir=./static/script

# Copy files into the release repository

cp -rT ./apps        $release_repo_path/apps
cp -rT ./docs        $release_repo_path/docs
cp -rT ./django_site $release_repo_path/django_site
cp -rT ./lib         $release_repo_path/lib
cp -rT ./00_script   $release_repo_path/00_script
cp -rT ./static      $release_repo_path/static
cp -rT ./templates   $release_repo_path/templates

cp ./README.md        $release_repo_path/README.md
cp ./manage.py        $release_repo_path/manage.py
cp ./pyproject.toml   $release_repo_path/pyproject.toml
cp ./.env_example     $release_repo_path/.env_example

cat > $release_repo_path/.gitignore <<EOF
.venv
.env
*.pyc
/django_site/security.py
EOF
